from haystack import indexes
from .models import Article


class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
    # 类名必须为需要检索的Model_name+Index，这里需要检索Article，所以创建ArticleIndex
    # use_template=True在text字段，这样就允许我们使用数据模板去建立搜索引擎索引的文件，说得通俗点就是索引里面需要存放一些什么东西
    text = indexes.CharField(document=True, use_template=True)  # 创建一个text字段
    # 以索引查询到的返回内容
    title = indexes.CharField(model_attr='title')
    desc = indexes.CharField(model_attr='desc')
    content = indexes.CharField(model_attr='content')

    def get_model(self):
        '''
        重载get_model方法，必须要有！
        返回建立索引的对应模型
        '''
        return Article

    def index_queryset(self, using=None):
        '''返回要建立索引的数据查询集  get.all'''
        return self.get_model().objects.filter(status=Article.STATUS_NORMAL)
        # return self.get_model().objects.all()
        # return self.get_model()._default_manager.all()

'''
./manage.py rebuild_index

mysql ---> model ---> serializer ---> view 
es ---> haystack ---> haystack_serializer ---> haystack_view

GET haystack/_search
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 14,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "haystack",
        "_type" : "modelresult",
        "_id" : "blog.article.2",
        "_score" : 1.0,
        "_source" : {
          "id" : "blog.article.2",
          "django_ct" : "blog.article",
          "django_id" : "2",
          "text" : """docker windows 7""",
          "desc" : ""
        }
      },
      ...
      ...
      ...
    ]
  }
}

'''


# def test_jieba():
#     import jieba
#     str = '二进制可执行文件， 主要用户应用'.replace(' ', '')
#     res = jieba.cut(str, cut_all=True)
#     for val in res:
#         print(val)
#
# test_jieba()